package com.zxcl.controller;

import com.alibaba.fastjson2.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.zxcl.constant.BusinessEnum;
import com.zxcl.model.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("admin/file")
@Api(tags = "文件上传接口")
public class FileController {
    /**
     * 文件上传
     *
     */
    @ApiOperation("上传文件到七牛云")
    @PostMapping("/upload/element")
    public Result upload(MultipartFile file){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "MZuVOaurBxrlR3X10JjepFC9d5QkA_p0Le_oPMhE";
        String secretKey = "xx3GBD-yOuyCFISTCQGEaysTt75GlmGnmAeVGhfq";
        String bucket = "hah-mall";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(file.getInputStream(), key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet defaultPutRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            // 返回一个地址 名字  rskx7xddy.hn-bkt.clouddn.com/defaultPutRet.hash     s0fw45vn3.hn-bkt.clouddn.com
            return Result.success("http://s0fw45vn3.hn-bkt.clouddn.com/" + defaultPutRet.hash);
        } catch (Exception ex) {
            return Result.fail(BusinessEnum.SERVER_INNER_ERROR);
        }

    }
}
